#!/usr/bin/python2
# -*- coding: utf-8 -*-
from PyQt4 import QtGui,QtCore
import sys,os
import threading
import thread
import json
import datetime
import base64
from window import Ui_MainWindow
from pyIpclient import *
from icon import img

class StartQT4(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.get_config()
        self.open_ip = StartThread()
        
        #信号与槽
        QtCore.QObject.connect(self.ui.pushButton_start,QtCore.SIGNAL("clicked()"), self.start_solt)#开始
        QtCore.QObject.connect(self.ui.pushButton_stop,QtCore.SIGNAL("clicked()"), self.stop_solt)#开始
        QtCore.QObject.connect(self.ui.pushButton_hide,QtCore.SIGNAL("clicked()"), self.hide_solt)#开始
        QtCore.QObject.connect(self.ui.pushButton_quit,QtCore.SIGNAL("clicked()"), self.quit_solt)#开始
        self.open_ip.logemit.connect(self.set_msg)
        QtCore.QObject.connect(self.ui.checkBox_autologin,QtCore.SIGNAL("clicked()"), self.set_config)
        QtCore.QObject.connect(self.ui.checkBox_autoreport,QtCore.SIGNAL("clicked()"), self.set_config)
        QtCore.QObject.connect(self.ui.checkBox_readuser,QtCore.SIGNAL("clicked()"), self.set_config)
        QtCore.QObject.connect(self.ui.checkBox_remember,QtCore.SIGNAL("clicked()"), self.set_config)
        
        #设置一个iconComboBox
        
        self.iconComboBox = QtGui.QComboBox()
        self.iconComboBox.addItem(
            QtGui.QIcon('.temp.ico'), "IPclient")

        #-------------------通知区域图标右键菜单start------------------
        self.minimizeAction = QtGui.QAction(u"最小化", self,
                triggered=self.hide)
        self.restoreAction = QtGui.QAction(u"&显示窗口", self,
                triggered=self.showNormal)
        self.quitAction = QtGui.QAction(u"&退出", self,
                triggered=QtGui.qApp.quit)
        #弹出的菜单的行为，包括退出，还原，最小化
        self.trayIconMenu = QtGui.QMenu(self)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addAction(self.minimizeAction)
        self.trayIconMenu.addAction(self.quitAction)
        self.trayIcon = QtGui.QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)
        #-------------------通知区域图标右键菜单end------------------
        #设置通知区域的ICON
        self.iconComboBox.currentIndexChanged.connect(self.setIcon)
 
        #通知区域icon显示
        self.iconComboBox.setCurrentIndex(1)
        self.trayIcon.show()
        self.trayIcon.activated.connect(
            self.iconActivated)
 
        #设定弹出主窗口的标题和大小
        self.setWindowTitle(u"ipclient")
        self.resize(400, 300)
        
        
        
    def start_solt(self,data=None):
        
        ConfData.start_flag = True
        ConfData.username = str(self.ui.lineEdit_username.text())
        ConfData.password = str(self.ui.lineEdit_password.text())
        self.open_ip.start()
        
        
    def stop_solt(self):
        ConfData.start_flag = False
        
    def hide_solt(self):
        self.hide()
        
    def quit_solt(self):
        QtGui.qApp.quit()
    
    def get_config(self):
        i = datetime.now()
        ConfData.month  = int(i.month)
        try:
            conf = open('.setting.json')
            djson = json.load(conf)
            ConfData.auto_login = djson['auto_login']
            ConfData.read_user  = djson['read_user']
            ConfData.remember   = djson['remember']
            ConfData.repet      = djson['repet']
            ConfData.count      = djson['startnumber']
            #ConfData.month        = djson['month']
            conf.close()
            if ConfData.auto_login is False: self.ui.checkBox_autologin.setCheckState(QtCore.Qt.Unchecked)
            if ConfData.read_user is False: self.ui.checkBox_readuser.setChecked(QtCore.Qt.Unchecked)
            if ConfData.remember is False: self.ui.checkBox_remember.setChecked(QtCore.Qt.Unchecked)
            if ConfData.repet is False: self.ui.checkBox_autoreport.setChecked(QtCore.Qt.Unchecked)
            if djson['month'] < ConfData.month : 
                ConfData.count = 0
                self.set_config()
                
            conf.close()
        except Exception as e:
            self.set_config()
    def set_config(self):
        try:
            conf = open('.setting.json','w+')
            setting = {"auto_login":self.ui.checkBox_autologin.isChecked(),
                       "read_user":self.ui.checkBox_readuser.isChecked(),
                       "remember":self.ui.checkBox_remember.isChecked(),
                       "repet":self.ui.checkBox_autoreport.isChecked(),
                       "startnumber":ConfData.count,
                       "month":ConfData.month}
            
            conf.write(json.dumps(setting))
            conf.close()
            self.get_config()
        except Exception as e:
            self.set_msg('error setting')        
      
    def set_msg(self,msg):
        self.ui.label_log.setText(msg)
        self.ui.lineEdit_username.setText(ConfData.username)
        self.ui.lineEdit_password.setText(ConfData.password)
        
        
    def iconActivated(self, reason):
        if reason in (QtGui.QSystemTrayIcon.Trigger,
                      QtGui.QSystemTrayIcon.DoubleClick):
            self.showNormal()
        elif reason == QtGui.QSystemTrayIcon.MiddleClick:
            self.showMessage()
 
    def setIcon(self, index):
        icon = self.iconComboBox.itemIcon(0)
        self.trayIcon.setIcon(icon)
        self.setWindowIcon(icon)
        self.trayIcon.setToolTip(
            self.iconComboBox.itemText(index))
 
    def showMessage(self):
        #这里是可以设置弹出对话气泡的icon的
        icon = QtGui.QSystemTrayIcon.MessageIcon()
        self.trayIcon.showMessage(
            ConfData.ipmsg,ConfData.str_money,icon,1000)
 
    def getTasksNum(self):
        self.showMessage()
        self.showMessage()
class StartIpclient(Ipclient):
    def __init__(self):
        self.is_init_sock = False
        self.is_login = False
    def open_ip(self):
        if self.is_login is True:
            self.is_login,r = self.refresh_online()
            if  self.is_login:
                ConfData.str_flow,ConfData.str_money = r
            elif self.is_login is False:
                ConfData.ipmsg = r
            return 10
        userid   = ConfData.username
        password = ConfData.password
        if len(userid) < 5 and len(password) < 5:            
            ConfData.ipmsg = u'请输入账号密码'
            return 1
        self.close_sock()
        self.init_sock(userid, password)        
        res, reply_msg = self.login()
        ConfData.ipmsg = reply_msg
        if res is False:
            if reply_msg == u'userid or password error.\n用户名或密码错误':
                return 3
            if reply_msg == u'failed to connect to server':
                return 2
            else:
                return 4
        res, msg = self.refresh_0A()
        if res is False:
            ConfData.ipmsg = msg
            return 4
        res, t = self.refresh_online()
        if res is False:
            ConfData.ipmsg = t
            return 4
        str_flow, str_money = t
        ConfData.str_flow = str_flow
        ConfData.str_money = str_money
        self.is_login = True
        return 10
class ConfData(object):
    username = ''
    password = ''
    ipmsg = ''
    str_flow ='' 
    str_money = ''
    
    start_flag = True
    
    auto_login = True
    read_user  = True
    remember   = True
    repet      = True
    
    count = 0
    month = 1
    
    def __init__(self):
        self.username = ''
        self.password = ''
    def get_username(self):
        return self.username
    def get_password(self):
        return self.password
    def set_msg(self,msg):
        self.ipmsg = msg

class StartThread(QtCore.QThread):
    logemit = QtCore.pyqtSignal(str)    
    def __int__(self):  
        super(StartThread,self).__init__()
        
    def run(self):
        if ConfData.auto_login:
            self.auto_login()
        else:
            self.sever_flag = True
            self.open_client = StartIpclient()
            is_open = self.open_client.open_ip()
            self.show_msg(ConfData.ipmsg + u'\t' + ConfData.str_money)
            while ConfData.start_flag and is_open == 10:
                QtCore.QThread.sleep(30)
                self.show_msg(ConfData.ipmsg + u'\t' + ConfData.str_money)
                
    def auto_login(self):
        try:
            self.fq = open("users.txt","r")
            self.line = self.fq.readline()
            self.count = ConfData.count
        except:
            self.show_msg(u"Open File Fail,Please Creat users.txt")
            self.count = 0
            return 0     
        if self.count == "":
                self.count = 0
        self.counts = int(self.count)
        self.st = 1

        self.pass_count = 0
        
        self.sever_flag = True
        self.open_client = StartIpclient()
        while ConfData.start_flag:
            self.read_user()
            is_open = self.open_client.open_ip()
            #3是密码错误 2是连接服务器失败  1是账户或密码为空 4是其他错误 10是开放成功
            if is_open == 10:
                self.show_msg(ConfData.ipmsg + u'\t' + ConfData.str_money)
                QtCore.QThread.sleep(15)
                self.sever_flag = False
                ConfData.count = self.st
                self.set_config(self.st)
                
            elif is_open == 2:
                self.show_msg(ConfData.ipmsg)
                self.sever_flag = False
                QtCore.QThread.sleep(60)
            elif is_open == 3:
                self.show_msg(ConfData.ipmsg)
                self.sever_flag = True
                self.st += 1
                self.pass_count += 1
                if self.pass_count >= 20:
                    QtCore.QThread.sleep(2)
                    if self.pass_count >=40:
                        self.pass_count = 0
            elif is_open == 4:
                self.show_msg(ConfData.ipmsg)
                QtCore.QThread.sleep(15)
                self.sever_flag = True
                self.st += 1
            elif is_open == 1:
                self.show_msg(ConfData.ipmsg)
                QtCore.QThread.sleep(1)
                self.sever_flag = True
                self.st += 1
        else:
            self.show_msg(u'已停止')
        
        QtCore.QThread.sleep(15)
        self.show_msg(u'发呆中.............')    
    def set_config(self,num=0):
        try:    
            conf = open('.setting.json','r')
            djson = json.load(conf)
            conf.close()
            conf = open('.setting.json','w+')
            djson['startnumber'] = num
            if djson['month'] < ConfData.month : djson['month'] = ConfData.month
            outStr = json.dumps(djson)
            conf.write(outStr)
            conf.close()
        except Exception as e:
            print e
    def show_msg(self,msg):
        self.logemit.emit(msg)
    def read_user(self): 
        while True:
            if self.st < self.counts:
                self.line = self.fq.readline()
                self.st = self.st + 1
                #print st,counts
                continue
            elif self.st >= self.counts and self.sever_flag:
                self.line = self.fq.readline()
            
            
            if self.line and self.sever_flag:
                self.line = self.line.split()
                userid = self.line[0]
                password = self.line[1]
                ConfData.username = userid
                ConfData.password = password
                #print self.counts,userid,password
                break
            elif not self.sever_flag:
                break
       
def main():
    pass
    

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    
    
    
    tmp = open(".temp.ico","wb+")
    tmp.write(base64.b64decode(img))
    tmp.close()
    
    myapp = StartQT4()
    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap(u".temp.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    myapp.setWindowIcon(icon) 
    
    myapp.show()
    
    sys.exit(app.exec_())